using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Core;

namespace Forum.Business
{
    public class SectionEdit : ForumUserControl,
        IReplyConverter<SectionReply, GetOperation>
    {
        protected ValuedTextBox subjectTextBox;
        protected ValuedTextBox groupTextBox;
        protected ValuedCheckBox enabledCheckBox;
        protected ResourceButton saveButton;

        private Section section;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetSectionRequest(this));
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!ValidatePermission(PermissionType.SectionAdmin))
            {
                throw new Exception("Access denied.");
            }
            saveButton.Click += new EventHandler(SaveSection);
        }

        private void BindData()
        {
            if (section != null)
            {
                subjectTextBox.Value = section.Subject.Value;
                enabledCheckBox.Checked = section.Enabled.Value == 1 ? true : false;

                Group group = BusinessManager.GetGroup(section.GroupId.Value);
                if (group != null)
                {
                    groupTextBox.Value = group.Subject.Value;
                }
            }
        }
        private void SaveSection(object sender, EventArgs e)
        {
            if (section != null)
            {
                section.Enabled.Value = enabledCheckBox.Checked ? 1 : 0;
                section.Subject.Value = subjectTextBox.Value;

                BusinessManager.UpdateSection(section);
                Page.Response.Redirect(UrlManager.Instance.FormatUrl("section_list", section.GroupId.Value));
            }
        }

        #region IReplyConverter<SectionReply,GetOperation> Members

        public void ConvertReply(SectionReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                section = reply.Entity as Section;

                if (!IsPostBack)
                {
                    BindData();
                }
            }
        }

        #endregion
    }
}